import { SourceKey, ProcessedItem } from './types';
import { getSources } from "./registrys";

import { NotFoundSourceError } from '../framework/utils/AppError';

/**
 * 验证key是否有效
 * @param key 
 * @returns 
 */
export async function isValidSourceKey(key: string): Promise<boolean> {
    const allSources = await getSources();
    return key in allSources;
}

/**
 * 主执行函数,获取数据源结果
 * @param key 
 * @returns 
 */
export async function getterSources(key: SourceKey): Promise<ProcessedItem[]> {
    const allSources = await getSources();
    const sourceFunction = allSources[key];
    if (!sourceFunction) {
        throw new NotFoundSourceError(`未找到与key [${key}] 对应的数据源`);
    }
    return await sourceFunction();
}

/**
 * 批量执行多个源函数
 * @param keys 
 * @returns 
 */
export async function getterSourcesMultipleSources(keys: SourceKey[]): Promise<Record<string, ProcessedItem[]>> {
    const results: Record<string, ProcessedItem[]> = {};

    for (const key of keys) {
        if (await isValidSourceKey(key)) {
            results[key] = await getterSources(key);
        } else {
            console.warn(`跳过无效的key: ${key}`);
        }
    }
    return results;
}
